package com.yunfeng.supercall.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;

import com.lin.utils.Parameters;
import com.ly.quickdev.library.utils.ImageTools;
import com.ly.quickdev.library.utils.ImageTools.OnBitmapCreateListener;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.PinterestCircleBitmapDisplayer;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.app.AppContext;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.httputils.HttpClient;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.httputils.UploadUtilsAsyncTask;
import com.yunfeng.supercall.httputils.UploadUtilsAsyncTask.OnUplaodListener;

public class PersonalDetailActivity extends BaseActivity {
	ImageTools mImageTools;
	private Bitmap mBitmap;
	UserBean mUser;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_personal_detail);
		mImageTools = new ImageTools(this);
		mUser = getUser(getActivity());
		refresh();
		findView(R.id.iv).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				List<String> list = new ArrayList<String>();
				list.add(mUser.getPhoto());
//				startActivity(new Intent(PersonalDetailActivity.this,
//						ViewPhotoActivity.class).putStringArrayListExtra(
//						KEY_DATA, (ArrayList<String>) list));
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		loadCallTime();
	}

	private void refresh() {
//		AppContext.displayImgWithDefault1((ImageView) findView(R.id.iv),
//				mUser.getPhoto());
		DisplayImageOptions optionsCircle;
		
		optionsCircle = new DisplayImageOptions.Builder()
		/*			.showImageOnFail(R.drawable.default_avatar)
		.showImageOnLoading(R.drawable.default_avatar)*/
		.displayer(new PinterestCircleBitmapDisplayer(20))
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();
		
		
		ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + mUser.getPhoto(), (ImageView) findView(R.id.iv), optionsCircle);
		setTextViewText(R.id.super_number, mUser.getSuperNumber());
		setTextViewText(R.id.nick_name, mUser.getNick_name());
		setTextViewText(R.id.addr, mUser.getAddress());
		setTextViewText(R.id.sex, getString(mUser.getSex() == 1 ? R.string.male
				: R.string.famale));
		setTextViewText(R.id.sign, mUser.getNote());
	}

	public void changeAddr(View v) {
		Intent intent = new Intent(this, InputActivity.class);
		intent.putExtra(KEY_DATA, mUser.getAddress());
		startActivityForResult(intent , 400);
	}

	public void changeName(View v) {
//		startActivityForResult(new Intent(this, InputActivity.class), 401);
		Intent intent = new Intent(this, InputActivity.class);
		intent.putExtra(KEY_DATA, mUser.getNick_name());
		startActivityForResult(intent , 401);
	}

	public void changeSign(View v) {
//		startActivityForResult(new Intent(this, InputActivity.class), 402);
		Intent intent = new Intent(this, InputActivity.class);
		intent.putExtra(KEY_DATA, mUser.getNote());
		startActivityForResult(intent , 402);
	}

	public void changeAvatar(View v) {
		mImageTools.showGetImageDialog(getString(R.string.choose_photo));
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case ImageTools.CAMARA:
				mImageTools.getBitmapFromCamara(new OnBitmapCreateListener() {

					@Override
					public void onBitmapCreate(Bitmap bitmap, String path) {
						// TODO Auto-generated method stub
						mImageTools.startZoomPhoto(
								Uri.fromFile(new File(path)), 160, 160);
					}
				});
				break;
			case ImageTools.BITMAP:
				mBitmap = mImageTools.getBitmapFromZoomPhoto(data);
				uploadAvatar();
				break;
			case ImageTools.GALLERY:
				mImageTools.startZoomPhoto(data.getData(), 160, 160);

				break;
			case 400:
				changeInfo("", data.getStringExtra(KEY_DATA), "", "");
				break;
			case 401:
				changeInfo(data.getStringExtra(KEY_DATA), "", "", "");
				break;
			case 402:
				changeInfo("", "", data.getStringExtra(KEY_DATA), "");
				break;
			}
		}
	}

	private void loadCallTime() {
		JSONObject json = BaseActivity.getBaseParams(getActivity());
		mHttpClient.post(FUNCTION_GET_USER_CALL_TIME, json,
				new MyAjaxCallBack() {

					@Override
					public void onReceiveError(String msg, String errorCode) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onReceiveData(String data, String msg) {
						// TODO Auto-generated method stub
						try {
							JSONObject json = new JSONObject(data.substring(1,
									data.length() - 1));
							setTextViewText(
									R.id.use_time,
									getResources().getQuantityString(
											R.plurals.days,
											json.getInt("onlineday"),
											json.getInt("onlineday")));
							int sec = json.getInt("calltime");
							if (sec < 60) {
								setTextViewText(
										R.id.call_time,
										getString(R.string.time_format_second,
												sec));
							} else {
								setTextViewText(
										R.id.call_time,
										getString(R.string.time_format_minute,
												sec / 60, sec % 60));
							}

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});
	}

	public void uploadAvatar() {
		File myCaptureFile = new File(Environment.getExternalStorageDirectory()
				.getAbsolutePath() + "/.super/");
		if (!myCaptureFile.exists()) {
			myCaptureFile.mkdirs();
		}
		myCaptureFile = new File(myCaptureFile.getAbsolutePath() + "/"
				+ System.currentTimeMillis() + ".jpeg");
		BufferedOutputStream bos;
		try {
			bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
			bos.flush();
			bos.close();
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		showProgressDialog(R.string.uploading_avatar);
		UploadUtilsAsyncTask mUploadUtils = new UploadUtilsAsyncTask(new OnUplaodListener() {

			@Override
			public void onUploadSuccess(String data) {
				// TODO Auto-generated method stub
				changeInfo("", "", "", data);
			}

			@Override
			public void onUploadError(String error) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onUpload(long current, long total, long progress) {
				// TODO Auto-generated method stub

			}
		});
		mUploadUtils.execute(myCaptureFile.getAbsolutePath(),
				HttpClient.UPLOAD_IMG_URL);
	}

	public void changeInfo(final String nick, final String addr,
			final String note, final String photo) {
		JSONObject json = getBaseParams(getActivity());
		try {
			json.put("i_nick_name", nick);
			json.put("i_address", addr);
			json.put("i_note", note);
			json.put("i_sex", mUser.getSex());
			json.put("i_photo", photo);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(FUNCTION_CHANGE_INFO, json, new MyAjaxCallBack() {

			@Override
			public void onReceiveError(String msg, String errorCode) {
				// TODO Auto-generated method stub
				showToast(msg);
				cancelProgressDialog();
			}

			@Override
			public void onReceiveData(String data1, String msg) {
				// TODO Auto-generated method stub
				showToast(R.string.edit_success);
				cancelProgressDialog();
				if (!TextUtils.isEmpty(nick)) {
					mUser.setNick_name(nick);
				}
				if (!TextUtils.isEmpty(note)) {
					mUser.setNote(note);
				}
				if (!TextUtils.isEmpty(addr)) {
					mUser.setAddress(addr);
				}
				if (!TextUtils.isEmpty(photo)) {
					mUser.setPhoto(photo);
				}

				refresh();
				getLoginManager(getActivity()).saveUser(mUser);

			}
		});
	}
}
